package org.iks.push.server;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.iks.push.codec.MessageCodec;
import org.iks.push.handler.AuthVerifyHandler;
import org.iks.push.handler.ChannelAuthInterceptor;
import org.iks.push.handler.ChatMessageHandler;
import org.iks.push.handler.JsonWebSocketFrameHandler;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.util.Properties;

/**
 * @author kzou
 * @date 2023/11/9 20:40
 * @description: websocket im server
 */
@Slf4j
@Service
public class WSPushServer implements CommandLineRunner, DisposableBean {

    @Value("${netty.ws.port}")
    private Integer port;

    @Value("${netty.ws.name}")
    private String name;

    @Value("${netty.ws.path}")
    private String path;

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    private final NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    private final NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    @Autowired
    private AuthVerifyHandler authVerifyHandler;

    @Autowired
    private ChannelAuthInterceptor channelAuthInterceptor;

    @Override
    public void run(String... args) {
        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline
                                .addLast(new HttpServerCodec())
                                .addLast(new ChunkedWriteHandler())
                                .addLast(new HttpObjectAggregator(2048))
                                .addLast(new WebSocketServerProtocolHandler(path))
                                .addLast(new JsonWebSocketFrameHandler())
                                .addLast(authVerifyHandler)
                                .addLast(channelAuthInterceptor)
                                .addLast(new ChatMessageHandler());
                    }
                });
        serverBootstrap.bind(port);
        registerNamingService(name, port);
    }

    private void registerNamingService(String nettyName, Integer nettyPort) {
        try {
            Properties properties = new Properties();
            properties.setProperty(PropertyKeyConst.SERVER_ADDR, nacosDiscoveryProperties.getServerAddr());
            properties.setProperty(PropertyKeyConst.NAMESPACE, nacosDiscoveryProperties.getNamespace());
            NamingService namingService = NamingFactory.createNamingService(properties);
            InetAddress address = InetAddress.getLocalHost();
            namingService.registerInstance(nettyName, address.getHostAddress(), nettyPort);
        } catch (Exception e) {
            log.warn("ws netty service register to nacos exception: {}", e.getMessage());
        }
    }

    @Override
    public void destroy() {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}
